﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ECCSystem.BizRule;
using ClsLogonDomain;
//using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Xml;
using System.IO;
namespace ECCSystem
{
    public partial class frmLogon : Form
    {
        DataAccess.ClsUserMaintenance objBRUser;
        BizRule.ClsSystemLog objBRLog;
        ClsLogonDomain.ClsLogonDomain.ClsLogonDomain objLogon;
		TcpListener _tl;
		BackgroundWorker _bwMessenger = null;
        public frmLogon()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Application.Exit();
        }

        private void btnLogon_Click(object sender, EventArgs e)
        {
            this.LogonSystem();
        }


        private void LogonSystem()
        {
            try
            {
                if (this.CheckInputItem() == true)
                {
                    objLogon = new ClsLogonDomain.ClsLogonDomain.ClsLogonDomain();
                    //define domain name
                    //string strDomain = "GECDALIAN";
					string strDomain = "DMACCOUNT";
					//string strDomain = "CHNCORP";
                    //if (objLogon.ntLogin(strDomain, txtLogonName.Text.Trim(), txtPWD.Text.Trim()) == false)
                    //{
                    //    MessageBox.Show("登録情報が誤っています！", "ECC Information");
                    //    return;
                    //}

                    DataSet objDS = new DataSet();
                    objBRUser = new ECCSystem.DataAccess.ClsUserMaintenance();
                    objDS = (DataSet)objBRUser.GetLoginUser(txtLogonName.Text.ToString().Trim());
                    if (objDS.Tables[0].Rows.Count < 1)
                    {
                        MessageBox.Show("当該ユーザーは見つかりません！", "ECC Information");
                        return;
                    }
                    BizRule.ClsCommon.gStrOperator = txtLogonName.Text.ToString().Trim();
                    BizRule.ClsCommon.gIntOperatorID = Convert.ToInt32(objDS.Tables[0].Rows[0][0].ToString());

					BizRule.ClsCommon.gStrOperatorName = objDS.Tables[0].Rows[0]["UserName"].ToString();
                    BizRule.ClsCommon.gStrRight = objDS.Tables[0].Rows[0][2].ToString();

                    //write system log
                    objBRLog = new ECCSystem.BizRule.ClsSystemLog();
                    objBRLog.AddSystemLog("Logon");
                    Form frmM = new frmMain();
                    frmM.Show();
					ClsCommon.gfrmMessage = new frmMessage();
					ClsCommon.gfrmMessage.Show();
					ClsCommon.gfrmMessage.btnStart_Click(null, null);

					string strIP = "";
					System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;

					for (int i = 0; i < addressList.Length; i++)
					{
						strIP += addressList[i].ToString();
					}
					ClsUserMaintenance objClsUserMaintenance = new ClsUserMaintenance();
					objClsUserMaintenance.EditUser(strIP);
                    this.Hide();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "ECC Catch Error");
            }
        }

        //Validate Data 
        private bool CheckInputItem()
        {
            if (txtLogonName.Text.ToString().Trim().Length == 0)
            {
                MessageBox.Show("登録名を入力してください！", "ECC Information");
                txtLogonName.Focus();
                return false;
            }
            if (txtPWD.Text.ToString().Trim().Length == 0)
            {
                MessageBox.Show("パスワードを入力してください！", "ECC Information");
                txtLogonName.Focus();
                return false;
            }
            return true;
        }

        //key down Enter
        private void frmLogon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.LogonSystem();
            }
        }
        private void txtLogonName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.LogonSystem();
            }
        }
        private void txtPWD_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.LogonSystem();
            }
        }

		private void frmLogon_Load(object sender, EventArgs e)
		{
			ReadXml();
			if (this._bwMessenger == null)
			{
				this._bwMessenger = new BackgroundWorker();
				this._bwMessenger.WorkerReportsProgress = true;
				this._bwMessenger.WorkerSupportsCancellation = true;

				this._bwMessenger.DoWork += MessageListener;
				this._bwMessenger.ProgressChanged += RcvedMessage;
				this._bwMessenger.RunWorkerAsync();
			}
		}

		public void MessageListener(object sender, DoWorkEventArgs e)
		{
			string rcvdMessage = "";
			int size = 1024;
			int lastsize = 0;
			int offset = 0;
			byte[] buffer = new byte[size];
			TcpClient tc;
			NetworkStream ns;
			this._tl = new TcpListener(1980);
			this._tl.Start();

			do
			{
				tc = this._tl.AcceptTcpClient();
				ns = tc.GetStream();
				do
				{
					offset += lastsize;
					lastsize = ns.Read(buffer, offset, size);
					rcvdMessage += System.Text.ASCIIEncoding.UTF8.GetString(buffer, 0, lastsize);
				} while (lastsize > size);

				this._bwMessenger.ReportProgress(0, rcvdMessage);
				System.Console.WriteLine(rcvdMessage);
				offset = 0;
				lastsize = 0;
				rcvdMessage = "";
				ns.Close();
				tc.Close();

			} while (e.Cancel == false);
		}

		public void RcvedMessage(object sender, ProgressChangedEventArgs e)
		{
			if (ClsCommon.gfrmMessage == null)
			{

				ClsCommon.gfrmMessage = new frmMessage();
				ClsCommon.gfrmMessage.Show();
			}
			else
			{
				ClsCommon.gfrmMessage.Close();
				ClsCommon.gfrmMessage = null;
			}

			ClsCommon.gfrmMessage = new frmMessage();
			ClsCommon.gfrmMessage.Show();
			
			ClsCommon.gfrmMessage.btnStart_Click(null, null);
		}

		#region "ReadXml"
		private void ReadXml()
		{
			XmlDocument xd = new XmlDocument();
			string str = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
			xd.Load(str + "xmlSet.xml");
			XmlNode node = xd.SelectSingleNode("//SQL");
			int nodesCount = node.ChildNodes.Count;
			for (int i = 0; i < nodesCount; i++)
			{

				string name = node.ChildNodes[i].LocalName;
				if ("StratTime".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{

					}
					else
					{
						ClsCommon.gStrStart = node.ChildNodes[i].InnerText;
					}

				}

				if ("endTime".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{

					}
					else
					{
						ClsCommon.gStrEnd = node.ChildNodes[i].InnerText;
					}
				}
			}

			node = xd.SelectSingleNode("//Appoint");
			nodesCount = node.ChildNodes.Count;
			for (int i = 0; i < nodesCount; i++)
			{

				string name = node.ChildNodes[i].LocalName;
				if ("Re".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{

					}
					else
					{
						ClsCommon.gstrRe = node.ChildNodes[i].InnerText;
					}

				}

				if ("ReLong".Equals(name))
				{
					if (node.ChildNodes[i].InnerText == null)
					{

					}
					else
					{
						ClsCommon.gstrReLong = node.ChildNodes[i].InnerText;
					}
				}
			}
		}
		#endregion

    }
}